/**
 * Copyright (C) 2011 Domenico Briganti <dometec@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package it.webrules.deploymanager.webapp.service.persistence;

import it.webrules.deploymanager.webapp.Constants;
import it.webrules.deploymanager.webapp.auth.DMPrincipal;
import it.webrules.deploymanager.webapp.service.BaseService;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.Map;

import javax.inject.Singleton;

@Singleton
public class StorageSystem extends BaseService {

	private File configDir;

	public StorageSystem() {

		logger.info("Initialize {}.", this.getClass().getName());

		String rootConfig = System.getProperty("catalina.base");
		if (rootConfig == null)
			rootConfig = ".";

		configDir = new File(rootConfig + "/conf/deploymanager/");
		logger.info("Configuration stored in {}.", configDir.getAbsolutePath());

		configDir.mkdirs();

	}

	public File getUserFile() {
		return getAbsolutePath(Constants.DB_USERFILE);
	}

	@SuppressWarnings("unchecked")
	public Map<String, DMPrincipal> read() throws IOException, ClassNotFoundException {
		try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(getUserFile()))) {
			return (Map<String, DMPrincipal>) in.readObject();
		}
	}

	public void save(Map<String, DMPrincipal> list) throws IOException {
		try (ObjectOutput out = new ObjectOutputStream(new FileOutputStream(getUserFile()))) {
			out.writeObject(list);
		}
	}

	public File getConfigRoot() {
		File path = getAbsolutePath(Constants.DB_CONFDIR);
		if (!path.exists())
			path.mkdirs();
		return path;
	}

	public Date getRootLastModified() {
		try {
			return getLastModified("");
		} catch (FileNotFoundException e) {
			String msg = "Root configuration path not found!";
			logger.error(msg, e);
			throw new RuntimeException(msg);
		}
	}

	public File getAbsolutePath(String path) {
		return new File(configDir.getAbsoluteFile() + File.separator + path);
	}

	public Date getLastModified(String path) throws FileNotFoundException {
		File env = getAbsolutePath(path);
		if (!env.exists())
			throw new FileNotFoundException(env.getAbsolutePath());
		return new Date(env.lastModified());
	}

	// public Collection<Entry> getRootEnvironment() throws
	// NumberFormatException, FileNotFoundException, IOException {
	// return getEnvironment("");
	// }
	//

	// public Collection<Entry> getEnvironment(String path) throws
	// NumberFormatException, FileNotFoundException, IOException {
	//
	// List<Entry> envs = new ArrayList<Entry>();
	// File envp = getAbsolutePath(path);
	// File[] files = envp.listFiles();
	// for (File file : files) {
	// if (file.isDirectory()) {
	// Entry environment = new Entry();
	// environment.name = file.getName();
	// environment.haschild = hasEnvChild(file);
	// envs.add(environment);
	// }
	// }
	//
	// return envs;
	//
	// }
	//
	// private boolean hasEnvChild(File file) {
	// File[] files = file.listFiles();
	// for (File sub : files)
	// if (sub.isDirectory())
	// return true;
	// return false;
	// }
	//
	// public boolean createEnv(String path) {
	// return getAbsolutePath(path).mkdirs();
	// }

	public boolean delete(String path) {
		return it.webrules.deploymanager.core.utils.FileUtils.deleteDirectory(getAbsolutePath(path));
	}

	// public Collection<Entry> getWebapps(String path) {
	// return getContent(path, ".dmc");
	// }
	//
	// public Collection<Entry> getStatics(String path) {
	// return getContent(path, ".dms");
	// }
	//
	// public Collection<Entry> getContent(final String path, final String
	// endWith) {
	// File rootEnv = getAbsolutePath(path);
	// File[] files = rootEnv.listFiles(new FilenameFilter() {
	// @Override
	// public boolean accept(File dir, String name) {
	// return name.endsWith(endWith);
	// }
	// });
	//
	// List<Entry> webapps = new ArrayList<Entry>();
	// for (File file : files) {
	// Entry entry = new Entry();
	// entry.name = file.getName();
	// entry.lastModified = new Date(file.lastModified());
	// webapps.add(entry);
	// }
	//
	// return webapps;
	// }

}
